import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.util.Base64;

public class URL_utils {
    public static final String PREFIX = "bjcloudvod://";

    public String decrypt(String url){
        if(url==null||url.length()==0||!url.contains(PREFIX)) {
            return null;
        }
        url = url.substring(PREFIX.length()).replaceAll("-","+").replaceAll("_","/");
        int pad = url.length()%4;
        switch (pad){
            case 2:{
                url += "==";
                break;
            }
            case 3:{
                url += "=";
                break;
            }
        }
        byte[] decode_res = Base64.getDecoder().decode(url);
        int factor = decode_res[0];
        int c = factor%8;
        StringBuilder sb = new StringBuilder();
        for(var i=1;i<decode_res.length;i++){
            int ch = decode_res[i]&0xFF;//只取出最低位，确保不出现负数
            int j = i-1;//调整下标
            int step =  ((j%4)*c + j%3 + 1);
//            System.out.println((char) (ch-step) + " " + (ch-step));
            sb.append((char) (ch-step));
        }
        return sb.toString();
    }

    public void download_video(int video_id,int course_id,String save_path) {
        try {
            NetReq n = new NetReq(new File("header"));
            String token_json = n.get(String.format("https://www.lexuemiao.com/api/app/getPlayToken/video_id=%d/course_id=%d", video_id, course_id));
            String token = JSONObject.parseObject(token_json).getJSONObject("data").getString("token");
            System.out.println(token_json);
            System.out.println("token = " + token);
            String vdinfo_json = n.get(String.format("https://api.baijiayun.com/vod/video/getAllFormatPlayUrl?vid=%d&sid=&render=jsonp&client_type=flash&ver=2&token=%s&_=%d"
                    , video_id, token, System.currentTimeMillis()));
            System.out.println(vdinfo_json);
            JSONObject data = JSONObject.parseObject(vdinfo_json).getJSONObject("data");
            JSONArray def = data.getJSONArray("definition");
            String quality = def.getJSONObject(Math.min(def.size() - 1, 2)).getString("type");
            String enc_url = data.
                    getJSONObject("all_format_play_info")
                    .getJSONObject("mp4")
                    .getJSONObject(quality).
                            getJSONArray("cdn_list").
                            getJSONObject(0).
                            getString("enc_url");
            System.out.println("enc_url = " + enc_url);
            System.out.println("url = " + decrypt(enc_url));
//            String title = data.getJSONObject("video_info").getString("title");
//            if (!title.endsWith(".mp4")) title += ".mp4";
            System.out.println("准备下载：" + save_path);
            n.download(decrypt(enc_url), save_path);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception{
        URL_utils u = new URL_utils();
        NetReq n = new NetReq(new File("header"));
        int video_id = 59297185;
        int course_id = 282;
        u.download_video(video_id,course_id,"test_dl/第2卷 合成词1.m3u8");
    }
}
